package cn.tannn.surenessdemo.util;

import cn.jdevelops.spring.core.context.ContextUtil;
import cn.tannn.surenessdemo.jwt.JwtConfig;
import com.usthe.sureness.util.JsonWebTokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author tnnn
 * @version V1.0
 * @date 2022-07-21 17:12
 */
public class JwtTokenUtil extends JsonWebTokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);

    /**
     *
     * @param subject 主题(这里是 用户的唯一值
     * @param roles 权限集合
     * @return String
     */
    public static String issueJwt(String subject, List<String> roles) {
        Map<String, Object> customClaimMap = Collections.singletonMap("roles", roles);
        JwtConfig jwtConfig = ContextUtil.getBean(JwtConfig.class);
        return issueJwtAll(UUID.randomUUID().toString(),
                subject,
                "tan",
                jwtConfig.getExpireTime() ,
                null,
                null,
                null,
                null,
                customClaimMap);
    }


    /**
     * 不管是否过期，都返回claims对象
     * @param token token
     * @return Claims
     */
    public static Claims parseJwtNoExpiredJwtException(String token){
        Claims claims;
        try {
            claims = JsonWebTokenUtil.parseJwt(token);
        } catch (ExpiredJwtException e) {
            logger.warn("token过期了",e);
            claims = e.getClaims();
        }
        return claims;
    }
}
